<?php
// +----------------------------------------------------------------------
// | nframework
// +----------------------------------------------------------------------
// | Author: King east <1207877378@qq.com>
// +----------------------------------------------------------------------


namespace ke;


class Config
{
    private static $config = [];

    public static function init()
    {
        $files = glob(ROOT_PATH . 'config/*.php');
        foreach ($files as $file) {
            $key = str_replace('.php', '', basename($file));
            $data = require($file);
            if (isset(self::$config[$key])) {
                self::$config[$key] = array_merge(self::$config[$key], $data);
            } else {
                self::$config[$key] = $data;
            }
        }
    }


    /**
     * 设置配置节点值
     * @param string $key
     * @param null $value
     */
    public static function set($key, $value = null)
    {
        if (is_null($value)) {
            self::$config = $key;
            return;
        }
        if (strpos($key, '.') === false) {
            $newConfig = [];
            $newConfig[$key] = $value;
            self::$config = array_merge(self::$config, $newConfig);
            return;
        }
        // 多级节点赋值
        $k = explode('.', $key);
        if (count($k) === 2) {
            self::$config[$k[0]][$k[1]] = $value;
        } else {
            self::$config[$k[0]][$k[1]][$k[2]] = $value;
        }

    }

    /**
     * 获取配置节点
     * @param string $key
     * @return array|mixed|null
     */
    public static function get($key = null)
    {
        if (is_null($key)) {
            return self::$config;
        }
        if (strpos($key, '.') === false) {
            return self::$config[$key];
        } else {
            $k = explode('.', $key);
            $d = self::$config;
            foreach ($k as $v) {
                if (isset($d[$v])) {
                    $d = $d[$v];
                } else {
                    return null;
                }
            }
            return $d;
        }
    }

}